<template>
  <ul class="list">
    <li
      class="item"
      v-for="item in letters"
      :key="item"
      @click="handleLetterClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      :ref="item"
    >{{item}}</li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    citys: Object
  },
  computed: {
    letters () {
      const letters = []
      for (const i in this.citys) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null,
      ccc: 0
    }
  },
  updated () {
    this.startY = this.$refs.A[0].offsetTop
  },
  methods: {
    handleLetterClick (e) { // 单击时进行跳转到某字母处
      this.$emit('change', e.target.innerHTML)
    },
    handleTouchStart (e) {
      this.touchStatus = true
    },
    handleTouchMove (e) { // 触摸时进行数字的跳转
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => { // 当以极快的速度滑动时不会触发跳转,而是会在执行前就被清除前一次的定时器
        if (this.touchStatus) {
          const touchY = e.touches[0].clientY - 79
          const index = Math.floor((touchY - this.startY) / 20)
          if (index >= 0 && index <= this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }
      }, 8)
    },
    handleTouchEnd (e) {
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.list
  display flex
  flex-direction column
  justify-content center
  position absolute
  top 1.58rem
  right 0
  bottom 0
  width 0.4rem
  .item
    line-height 0.4rem
    color $bgColor
    text-align center
</style>
